<template>
  <div class="ai-assistant-container">
    <el-container class="full-height">
      <!-- 侧边栏 - 历史对话 -->
      <el-aside width="250px" class="sidebar">
        <div class="sidebar-header">
          <h3>历史咨询</h3>
          <el-button 
            type="primary" 
            size="small" 
            @click="startNewChat"
            icon="el-icon-plus"
          >
            新建对话
          </el-button>
        </div>
        
        <el-scrollbar class="conversation-list">
          <div 
            v-for="conv in conversations" 
            :key="conv.id"
            class="conversation-item"
            :class="{ active: activeConversation === conv.id }"
            @click="switchConversation(conv.id)"
          >
            <el-icon><ChatLineRound /></el-icon>
            <span class="conv-title">{{ getConversationTitle(conv) }}</span>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              class="delete-btn"
              @click.stop="deleteConversation(conv.id)"
            />
          </div>
        </el-scrollbar>
      </el-aside>

      <!-- 主内容区 - 对话界面 -->
      <el-main class="chat-main">
        <div class="chat-header">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
              <h2>园区智能助手</h2>
              <p class="subtitle">24小时为您提供咨询服务</p>
            </div>
            <el-button type="text" size="medium" @click="router.push('/')" class="home-btn">
              <el-icon>
                <ArrowLeft />
              </el-icon>
              返回首页
            </el-button>
          </div>
        </div>
        
        <div class="chat-container">
          <!-- 消息列表 -->
          <div class="message-list" ref="messageList">
            <div 
              v-for="(message, index) in currentMessages" 
              :key="index"
              class="message-item"
              :class="message.role"
            >
              <div class="message-avatar">
                <el-avatar v-if="message.role === 'user'">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <el-avatar v-else style="background-color: #409EFF">
                  <el-icon><ChatDotRound /></el-icon>
                </el-avatar>
              </div>
              
              <div class="message-content">
                <div class="message-meta">
                  <span class="sender">{{ message.role === 'user' ? '我' : '园区助手' }}</span>
                  <span class="time">{{ formatTime(message.time) }}</span>
                </div>
                
                <div class="message-text">
                  <markdown-renderer 
                    v-if="message.content" 
                    :content="message.content"
                  />
                  <div v-else class="loading-animation">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
                
                <div v-if="message.attachments && message.attachments.length > 0" class="message-attachments">
                  <div 
                    v-for="(file, idx) in message.attachments" 
                    :key="idx"
                    class="attachment-item"
                  >
                    <el-link :href="file.url" target="_blank">
                      <el-icon><Document /></el-icon>
                      {{ file.name }}
                    </el-link>
                    <span class="file-size">({{ formatFileSize(file.size) }})</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 输入区域 -->
          <div class="input-area">
            <div class="toolbar">
              <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :http-request="handleFileUpload"
                multiple
                :limit="5"
              >
                <el-button type="text" icon="el-icon-paperclip"></el-button>
              </el-upload>
            </div>
            
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题..."
              resize="none"
              @keyup.enter.exact.prevent="sendMessage"
              class="message-input"
            />
            
            <div class="action-bar">
              <el-button 
                type="primary" 
                @click="sendMessage"
                :loading="isSending"
                :disabled="!userInput.trim()"
              >
                发送
              </el-button>
              <el-button @click="clearInput">
                清空
              </el-button>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ChatLineRound, 
  User, 
  Document,
  ChatDotRound,
  Paperclip
} from '@element-plus/icons-vue'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

const router = useRouter()

// 对话数据
const conversations = ref([])
const messages = ref({})

// 当前状态
const activeConversation = ref('')
const userInput = ref('')
const isSending = ref(false)
const messageList = ref(null)

// 初始化对话

const initConversations = () => {
  const savedConversations = localStorage.getItem('aiAssistantConversations')
  const savedMessages = localStorage.getItem('aiAssistantMessages')

  if (savedConversations) {
    conversations.value = JSON.parse(savedConversations)
    const rawMessages = JSON.parse(savedMessages || '{}')

    // ⭐ 转换所有 time 字段为 Date 实例
    for (const convId in rawMessages) {
      rawMessages[convId] = rawMessages[convId].map(msg => ({
        ...msg,
        time: new Date(msg.time)
      }))
    }

    messages.value = rawMessages

    if (conversations.value.length > 0) {
      activeConversation.value = conversations.value[0].id
    } else {
      startNewChat()
    }
  } else {
    // 初始示例数据
    startNewChat()
    addSampleData()
  }
}


// 添加示例数据
const addSampleData = () => {
  const conv1 = {
    id: 'conv-' + Date.now(),
    title: '园区服务咨询',
    createdAt: new Date(),
    updatedAt: new Date()
  }
  
  conversations.value.push(conv1)
  messages.value[conv1.id] = [
    {
      id: 'msg-' + Date.now(),
      role: 'assistant',
      content: '您好！我是园区智能助手，可以为您解答以下问题：\n\n1. 园区服务指南\n2. 设施报修流程\n3. 合同管理咨询\n4. 招商政策查询\n\n请问有什么可以帮您？',
      time: new Date(),
      attachments: []
    }
  ]
  
  activeConversation.value = conv1.id
  saveToLocalStorage()
}

// 保存到本地存储
const saveToLocalStorage = () => {
  localStorage.setItem('aiAssistantConversations', JSON.stringify(conversations.value))
  localStorage.setItem('aiAssistantMessages', JSON.stringify(messages.value))
}

// 计算当前对话的消息
const currentMessages = computed(() => {
  return messages.value[activeConversation.value] || []
})

// 获取对话标题
const getConversationTitle = (conv) => {
  if (conv.title) return conv.title
  const firstMessage = messages.value[conv.id]?.[0]
  return firstMessage?.content?.substring(0, 20) || '新对话'
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim()) return
  
  const newMessage = {
    id: 'msg-' + Date.now(),
    role: 'user',
    content: userInput.value,
    time: new Date(),
    attachments: []
  }
  
  // 添加到当前对话
  if (!messages.value[activeConversation.value]) {
    messages.value[activeConversation.value] = []
  }
  messages.value[activeConversation.value].push(newMessage)
  
  // 更新对话时间
  const conv = conversations.value.find(c => c.id === activeConversation.value)
  if (conv) {
    conv.updatedAt = new Date()
    conv.title = newMessage.content.substring(0, 20)
  }
  
  // 清空输入
  const inputText = userInput.value
  userInput.value = ''
  
  // 保存数据
  saveToLocalStorage()
  
  // 滚动到底部
  scrollToBottom()
  
  // 模拟AI回复
  isSending.value = true
  const aiReply = {
    id: 'msg-' + (Date.now() + 1),
    role: 'assistant',
    content: '',
    time: new Date(),
    attachments: []
  }
  messages.value[activeConversation.value].push(aiReply)
  
  // 模拟AI思考过程
  simulateAIResponse(inputText, aiReply)
}

// 模拟AI回复
const simulateAIResponse = (userInput, aiReply) => {
  const responses = {
    '报修': '园区报修流程：\n\n1. 登录园区服务平台\n2. 选择"设施报修"功能\n3. 填写报修信息并上传照片\n4. 提交后获取报修编号\n\n维修人员通常会在2小时内响应。',
    '合同': '合同相关服务：\n\n• 合同模板下载\n• 合同审批进度查询\n• 续签流程咨询\n• 纠纷处理指引\n\n您需要哪方面的帮助？',
    '停车': '园区停车指南：\n\n🅿️ 地上停车场：8:00-20:00免费\n🅿️ 地下车库：24小时开放，月卡300元/月\n🚗 访客停车：需在前台登记领取临时停车券',
    '招商': '2023年园区招商政策：\n\n✅ 首年租金减免30%\n✅ 税收优惠政策\n✅ 一站式企业服务\n✅ 配套人才公寓\n\n详情请联系招商部：8888-6666',
    '默认': `我已收到您的咨询："${userInput}"\n\n正在从园区知识库中为您查询相关信息，请稍候...`
  }

  let response = responses['默认']
  if (userInput.includes('报修')) response = responses['报修']
  if (userInput.includes('合同')) response = responses['合同']
  if (userInput.includes('停车')) response = responses['停车']
  if (userInput.includes('招商')) response = responses['招商']
  
  // 模拟打字效果
  let i = 0
  const typingInterval = setInterval(() => {
    if (i < response.length) {
      aiReply.content = response.substring(0, i + 1)
      i++
      scrollToBottom()
    } else {
      clearInterval(typingInterval)
      isSending.value = false
      saveToLocalStorage()
    }
  }, 20)
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

// 切换对话
const switchConversation = (convId) => {
  activeConversation.value = convId
  scrollToBottom()
}

// 新建对话
const startNewChat = () => {
  const newConvId = 'conv-' + Date.now()
  conversations.value.unshift({
    id: newConvId,
    title: '新对话',
    createdAt: new Date(),
    updatedAt: new Date()
  })
  messages.value[newConvId] = [
    {
      id: 'msg-' + Date.now(),
      role: 'assistant',
      content: '您好！我是园区智能助手，请问有什么可以帮您？',
      time: new Date(),
      attachments: []
    }
  ]
  activeConversation.value = newConvId
  saveToLocalStorage()
  scrollToBottom()
}

// 删除对话
const deleteConversation = (convId) => {
  ElMessageBox.confirm('确定删除此对话记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = conversations.value.findIndex(c => c.id === convId)
    if (index !== -1) {
      conversations.value.splice(index, 1)
      delete messages.value[convId]
      if (activeConversation.value === convId) {
        activeConversation.value = conversations.value[0]?.id || ''
        if (!activeConversation.value) {
          startNewChat()
        }
      }
      saveToLocalStorage()
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 清空输入
const clearInput = () => {
  userInput.value = ''
}

// 文件上传处理
const beforeUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  return true
}

const handleFileUpload = async (options) => {
  const file = options.file
  const newMessage = {
    id: 'msg-' + Date.now(),
    role: 'user',
    content: `[附件] ${file.name}`,
    time: new Date(),
    attachments: [
      {
        name: file.name,
        size: file.size,
        url: URL.createObjectURL(file)
      }
    ]
  }
  
  if (!messages.value[activeConversation.value]) {
    messages.value[activeConversation.value] = []
  }
  messages.value[activeConversation.value].push(newMessage)
  
  // 更新对话时间
  const conv = conversations.value.find(c => c.id === activeConversation.value)
  if (conv) {
    conv.updatedAt = new Date()
  }
  
  saveToLocalStorage()
  scrollToBottom()
}

// 监听对话变化自动滚动
watch(currentMessages, () => {
  scrollToBottom()
}, { deep: true })

// 初始化
onMounted(() => {
  initConversations()
})
</script>

<style scoped>
.ai-assistant-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.full-height {
  height: 100%;
}

.sidebar {
  background-color: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.conversation-list {
  flex: 1;
  padding: 10px 0;
}

.conversation-item {
  padding: 12px 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  position: relative;
  transition: background-color 0.3s;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.active {
  background-color: #ecf5ff;
}

.conversation-item .el-icon {
  margin-right: 10px;
  color: #909399;
}

.conv-title {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.chat-main {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.chat-header h2 {
  margin: 0;
  color: #303133;
}

.chat-header .subtitle {
  margin: 5px 0 0;
  color: #909399;
  font-size: 14px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #fff;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 15px;
}

.message-content {
  max-width: 70%;
}

.message-item.user .message-content {
  text-align: right;
}

.message-meta {
  margin-bottom: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.message-item.user .message-meta {
  justify-content: flex-end;
}

.sender {
  font-weight: bold;
  margin-right: 10px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.6;
  font-size: 15px;
}

.message-item.user .message-text {
  background-color: #409EFF;
  color: #fff;
}

.message-item.assistant .message-text {
  background-color: #f5f7fa;
  color: #303133;
  border: 1px solid #e4e7ed;
}

.message-attachments {
  margin-top: 10px;
}

.attachment-item {
  display: inline-flex;
  align-items: center;
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
}

.attachment-item .el-icon {
  margin-right: 5px;
}

.file-size {
  margin-left: 5px;
  color: #909399;
  font-size: 12px;
}

.input-area {
  padding: 15px 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}

.toolbar {
  margin-bottom: 10px;
}

.message-input {
  margin-bottom: 15px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
}

.loading-animation {
  display: inline-flex;
  align-items: center;
  height: 20px;
}

.loading-animation span {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin: 0 3px;
  background-color: #409EFF;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loading-animation span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-animation span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% { 
    transform: scale(0);
  }  
  40% { 
    transform: scale(1.0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-aside {
    width: 100% !important;
    height: 200px;
  }
  
  .message-content {
    max-width: 85%;
  }
}
</style>